#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <queue>
#include <stack>
#include <vector>
#include <iostream>
using namespace std;
#define MAX_SIZE 1000
typedef struct VNode *PtrToNode;
struct VNode {
    int id;
    PtrToNode Near;
};
typedef struct LGraph{
    PtrToNode Near;
} Adj[MAX_SIZE];
typedef struct input *PtrToi;
struct input{
    int v1;
    int v2;
    int cost;
};
//重载运算符 给priority用
bool operator < (input a, input b)
{
    return a.cost < b.cost;
}
bool operator > (input a, input b)
{
    return a.cost > b.cost;
}
bool CheckU(int S[], int v1, int v2);
void Union(int S[], int v1, int v2);
int Find(int S[], int X);
int main()
{
    int N, M,v1,v2,cost;
    int SumCost = 0;
    int S[MAX_SIZE];//并查集所用
    scanf("%d %d", &N, &M);
    Adj LGraph;
    priority_queue<input, vector<input>, greater<input>> minheap;
    PtrToi temp = (PtrToi)malloc(sizeof(input));
    PtrToNode NewNode;
    for (int i = 0; i < M;i++)
    {
        
        scanf("%d %d %d", &v1, &v2, &cost);
        v1--;
        v2--;
        NewNode = (PtrToNode)malloc(sizeof(VNode));
        NewNode->id = v2;
        NewNode->Near = LGraph[v1].Near;
        LGraph[v1].Near = NewNode;

        NewNode = (PtrToNode)malloc(sizeof(VNode));
        NewNode->id = v1;
        NewNode->Near = LGraph[v2].Near;
        LGraph[v2].Near = NewNode;
        temp->v1 = v1;
        temp->v2 = v2;
        temp->cost = cost;
        minheap.push(*temp);
    }
    for (int i = 0; i < N; i++)
    {
        S[i] = -1;
    }
    while (!minheap.empty())
    {
        *temp = minheap.top();
        minheap.pop();
        v1 = temp->v1;
        v2 = temp->v2;
        if (CheckU(S,v1,v2))
            SumCost = SumCost + temp->cost;
    }
    int cout = 0;
    for (int i = 0; i < N; i++)
    {
        if(S[i]<0)
            cout++;
        if(cout>1)
            break;
    }
    if(cout>1)
        printf("-1");
    else
        printf("%d", SumCost);
    return 0;
}
bool CheckU(int S[],int v1,int v2)
{
    int Root1, Root2;
    Root1 = Find(S, v1);
    Root2 = Find(S, v2);
    if (Root1 == Root2)
        return false;
    else
        Union(S, Root1, Root2);
    return true;
}
void Union(int S[],int v1,int v2)
{
    if(S[v1]<S[v2])//集合1大
    {
        S[v1] += S[v2];//并入
        S[v2] = v1;//根换成v1
    }
    else
    {
        S[v2] += S[v1];
        S[v1] = v2;
    }
}
int Find(int S[],int X)
{
    if(S[X]<0)
        return X;
    else
        return S[X] = Find(S, S[X]);
}